<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Order extends Backend
{
     // 设置关联查询
     protected $relationSearch = true;

     // 当前模型
     protected $model = null;
 
     // 无需登陆
     protected $noNeedLogin = [];
     // 无需鉴权
     protected $noNeedRight = [];

     public function __construct(){
          parent::__construct();
          $this->model = model('Product.order.Order');
          $this->OrderProductModel = model('Product.order.Product');

          $this->assign('statusList',$this->model->getStatusList());          
     }

     public function index(){
          $this->request->filter(['strip_tags','trim']);

          if($this->request->isAjax()){
               if ($this->request->request('keyField')) {
                    return $this->selectpage();
                }
    
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    
                $total = $this->model
                    ->with(['express','business'])
                    ->where($where)
                    ->order($sort,$order)
                    ->limit($offset,$limit)
                    ->count();

                $list = $this->model
                    ->with(['express','business'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset,$limit)
                    ->select();
                $result = [
                    'total' => $total, 
                    'rows' => $list
               ];
    
                return json($result);
          }


          return $this->view->fetch();
     }

     public function del($ids=NULL){
          $ids = $this->request->param('ids',[],'trim');

          $list = $this->model->select($ids);
          if(!$list){
               $this->error(__('No Results were found'));
               exit;
          }

          $result = $this->model->destroy($ids);

          if($result === FALSE){
               $this->error('删除失败');
               exit;
          }else{
               $this->success('删除成功');
          }
     }

     public function info($ids=NULL){
          $row = $this->model
               ->with(['business','express','sale','review','dispatched','address'=>['provinces','citys','districts']])
               ->find($ids);

          if(!$row){
               $this->error(__('No Results were found'));
               exit;
          }

          $OrderProductData = $this->OrderProductModel
                         ->with(['products'])
                         ->where(['orderid' => $ids])
                         ->select();
               
          $this->assign([
               'row' => $row,
               'OrderProductData' => $OrderProductData
          ]);


          return $this->view->fetch();
     }

     // 发货
     public function deliver($ids=NULL){
          $row = $this->model->find($ids);
          if(!$row){
               $this->error(__('No Results were found'));
               exit;
          }

          if($this->request->isPost()){
               $params = $this->request->param('row/a');

               $data = [
                    'id' => $ids,
                    'expressid' => $params['expressid'],
                    'expresscode' => $params['expresscode'],
                    'shipmanid' => $this->auth->id,
                    'status' => 2
               ];
               // 定义验证器
               $validate = [
                    [
                         'expressid' => 'require',
                         'expresscode' => 'require|unique:order'
                    ],
                    [
                         'expressid.require' => '配送物流未知',
                         'expresscode.unique' => '配送物流单号已存在，请重新输入',
                         'expresscode.require' => '请输入配送物流单号'
                    ]
               ];

               $result = $this->model->validate(...$validate)->isUpdate(true)->save($data);

               if($result === FALSE){
                    $this->error($this->model->getError());
                    exit;
               }else{
                    $this->success('发货成功');
                    exit;
               }
          }

          // 查看物流公司数据
          $ExpData = model('Express')->column('id,name');
          $this->assign([
               'ExpData' => $ExpData,
               'row' => $row
          ]);


          return $this->view->fetch();
     }

     // 退货
     public function refund($ids=NULL){
          $row = $this->model->find($ids);
          if(!$row){
               $this->error(__('No Results were found'));
               exit;
          }

          if($this->request->isPost()){
               $params = $this->request->param('row/a');

               if(empty($params['examinereason']) && $params['refund'] == 0) {
                    $this->error('请填写不同意退货的原因');
               }    
               
               // 同意仅退款
               if($params['refund'] == '1' && $row['status'] == '-1'){
                    $BusinessModel = model('Business.User');
                    $model = model('Product.order.Order');
                    $business = $BusinessModel->find($row['busid']);

                    if(!$business){
                         $this->error('客户不存在');
                         exit;
                    }
                    // 开启事务
                    $BusinessModel->startTrans();
                    $this->model->startTrans();
                    
                    // 更新用户余额
                    $BusinessData = [
                         'id' => $business['id'],
                         'money' => bcadd($row['amount'],$business['money'],2)
                    ];

                    $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);
                    
                    if($BusinessStatus === FALSE){
                         $this->error('更新用户余额失败');
                    }

                    // 更新订单状态
                    $OrderData = [
                         'id' => $ids,
                         'status' => -4
                    ];

                    $OrderStatus = $this->model->isUpdate(true)->save($OrderData);

                    if($OrderStatus === FALSE){
                         $BusinessModel->rollback();
                         $this->error('订单状态更新错误');
                    }
                    

                    if($BusinessStatus === FALSE || $OrderStatus === FALSE){
                         $BusinessModel->rollback();
                         $model->rollback();
                         $this->error('同意退款失败');
                    }else{
                         $BusinessModel->commit();
                         $model->commit();
                         $this->success('同意退款成功');
                    }
               }

               // 不同意退货
               if($params['refund'] == '0'){
                    // 封装数据
                    $data = [
                         'id' => $ids,
                         'status' => -5,
                         'examinereason' => $params['examinereason']
                    ];

                    //更新表
                    $result = $this->model->isUpdate(true)->save($data);
                    
                    if($result === FALSE){
                         $this->error($this->model->getError());
                    }else{
                         $this->success('处理完成');
                    }
               }

               // 同意退款也退货
               if($params['refund'] == '1' && $row['status'] == '-2'){
                    $BusinessModel = model('Business.User');
                    $model = model('Product.order.Order');
                    $business = $BusinessModel->find($row['busid']);

                    if(!$business){
                         $this->error('客户不存在');
                         exit;
                    }

                    // 开启事务
                    $BusinessModel->startTrans();
                    $this->model->startTrans();
                    
                    // 更新用户余额
                    $BusinessData = [
                         'id' => $business['id'],
                         'money' => bcadd($row['amount'],$business['money'],2)
                    ];

                    $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);
                    
                    if($BusinessStatus === FALSE){
                         $this->error('更新用户余额失败');
                    }

                    // 更新订单状态
                    $OrderData = [
                         'id' => $ids,
                         'status' => -3
                    ];

                    $OrderStatus = $this->model->isUpdate(true)->save($OrderData);

                    if($OrderStatus === FALSE){
                         $BusinessModel->rollback();
                         $this->error('订单状态更新错误');
                    }
                    

                    if($BusinessStatus === FALSE || $OrderStatus === FALSE){
                         $BusinessModel->rollback();
                         $model->rollback();
                         $this->error('同意退货退款失败');
                    }else{
                         $BusinessModel->commit();
                         $model->commit();
                         $this->success('同意退货退款成功');
                    }
               }

          }

          $this->assign([
               'row' => $row
          ]);
          return $this->view->fetch();
     }

     // 回收站
     public function recyclebin(){
          $this->request->filter(['strip_tags','trim']);

          if($this->request->isAjax()){
               //获取表格所提交过来筛选和排序的一些参数
               list($where, $sort, $order, $offset, $limit) = $this->buildparams();

               // 表格需要两个返回值参数 总条数和分页的数据
               $total = $this->model
                    ->onlyTrashed()
                    ->with(['express','business'])
                    ->where($where)
                    ->order($sort,$order)
                         ->count(); //返回查询的总数

                    // var_dump($total);
                    // exit;
                    $list = $this->model
                         ->onlyTrashed()
                         ->with(['express','business'])
                         ->where($where)
                         ->order($sort,$order)
                         ->limit($offset,$limit)
                         ->select();
                    // var_dump(collection($list)->toArray());
                    // exit;

                    // 打印sql语句
                    // echo $this->model->getLastSql();
                    // exit;

                    // 组装数据
                    $result = [
                         'total' => $total,
                         'rows' => $list
                    ];
                    // 返回给ajax的数据
                    return json($result);  

        }
          return $this->view->fetch();
     }
     
     // 恢复
     public function restore($ids=NULL){
          $ids = $ids ?: $this->requst->param('ids',0,'trim');
          $rows = $this->model->onlyTrashed()->select($ids);
          // var_dump(collection($rows)->toArray());
          // exit;

          if(!$rows){
               $this->error(__('No Results were found'));
               exit;
          }

          $result = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->update(['deletetime'=>NULL]);

          if($result === FALSE){
               $this->error('恢复订单失败');
               exit;
          }else{
               $this->success('恢复订单成功');
               exit;
          }
     }

     // 销毁
     public function destroy($ids=NULL){
          $ids = $ids ?: $this->request->param('ids',0,'trim');
          $rows = $this->model->onlyTrashed()->select($ids);

          // var_dump(collection($rows)->toArray());
          // exit;

          if(!$rows){
               $this->error(__('No Results were found'));
               exit;
          }

          $id = array_column($rows,"id");

          // 去重、去空
          $id = array_filter($id);
          $id = array_unique($id);

          // var_dump($id);
          // exit;
          $orderproduct = $this->OrderProductModel->where(['orderid'=>['IN',$ids]])->column('id');

          // var_dump(collection($orderproduct)->toArray());
          // exit;

          $this->model->startTrans();
          $this->OrderProductModel->startTrans();

          $result = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->delete(true);

          if($result === FALSE){
               $this->error('销毁订单失败');
               exit;
          }else{
               $ProductResult = $this->OrderProductModel->destroy($orderproduct);

               if($ProductResult === FALSE){
                    $this->model->rollback();
                    $this->error('销毁订单商品失败');
                    exit;
               }else{
                    $this->OrderProductModel->commit();
                    $this->model->commit();
                    $this->success('销毁订单成功');
                    exit;
               }
          }
          
     }

}
